# -*- coding: utf-8 -*-
from typing import Dict, Optional

from zinx.ziface.iconmanager import IConManager
from zinx.ziface.iconnection import IConnection


class ConManager(IConManager):
    """
    连接管理模块
    """

    def __init__(self):
        self.connections: Dict[int, IConnection] = {}

    def Add(self, Conn: IConnection):
        """
        添加链接
        :param Conn:
        :return:
        """
        self.connections[Conn.GetConnID()] = Conn
        print("链接添加至链接管理成功，当前数量 = ", self.Len())

    def Remove(self, Conn: IConnection):
        """
        删除连接
        :param Conn:
        :return:
        """
        del self.connections[Conn.GetConnID()]
        print("链接移除成功ConnID=", Conn.GetConnID(), "，当前数量 = ", self.Len())

    def Get(self, connID: int) -> Optional[IConnection]:
        """
        利用ConnID获取链接
        :param connID:
        :return:
        """
        if connID in self.connections.keys():
            return self.connections[connID]
        return None

    def Len(self) -> int:
        """
        获取当前连接个数
        :return:
        """
        return len(self.connections)

    def ClearConn(self):
        """
        删除并停止所有链接
        :return:
        """
        # 当进行key遍历时，如果dict被修改会抛出异常，使用copy做一个副本进行解决
        keys = self.connections.copy().keys()
        for key in keys:
            if key not in self.connections.keys():
                continue
            self.connections[key].Stop()
            try:
                del self.connections[key]
            except:
                continue
        print("清除所有链接: 当前数量 = ", self.Len())


# 创建一个链接管理
def NewConnManager() -> IConManager:
    cm = ConManager()
    return cm
